<template>
    <div class="articleDetail">
		<el-form :model="form">
		    <el-form-item label="标题">
		        <el-input v-model="form.title" />
		    </el-form-item>
			<el-form-item label="作者">
			    <el-input v-model="form.author" />
			</el-form-item>
		</el-form>
		<el-upload
		  class="upload-demo"
		  action
		  :auto-upload="false"
		  :on-preview="handlePreview"
		  :on-success="uploadSuccess"
		  :on-change="uploadSectionFile"
		  :file-list="fileList">
		  <el-button size="small" type="primary">点击上传封面</el-button>
		</el-upload>
		<div id="toolbar-container" class="toolbar"></div>
		<div id="text-container" class="text"></div>
		<!-- <button type="button" class="btn" @click="getEditorData">获取当前内容</button> -->
		<div class='btnGrop'>
			<el-button type="primary" @click="onSubmit">提交</el-button>
		</div>
    </div>
</template>

<script>
	import wangEditor from 'wangeditor' // 引入富文本编辑器
	import {uploadImg, uploadArticle} from '../../request/api/articleMange/articleMange.js'
	import {getCurrentTime} from '../../utils/index.js'
	import { ElMessage, ElMessageBox } from 'element-plus'
	
    export default {
        name: 'addNewArticle',
        components: {},
        data() {
            return {
                editor: null,
                editorData: '',
				input: '',
				fileList: [
					// {
					// 	name: 'food.jpeg',
					// 	url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
					// },
				],
				form: {
					title: '',
					author: ''
				},
				coverFile: ''
            }
        },
		mounted() {
			const editor = new wangEditor('#toolbar-container', '#text-container')
			// 配置 onchange 回调函数，将数据同步到 vue 中
			editor.config.onchange = (newHtml) => {
			   this.editorData = newHtml
			}
			editor.config.customUploadImg = function(resultFiles, insertImgFn) {
				// resultFiles 是 input 中选中的文件列表
				// insertImgFn 是获取图片 url 后，插入到编辑器的方法
			    const formData = new FormData()
			    for (let i = 0; i < resultFiles.length; i++) {
			        formData.append('file', resultFiles[i])
			    }
				uploadImg(formData)
				.then(res => {
					if (res.data) {
						res.data.map(i => {
							insertImgFn(i.imgPath ?? '')
						})
					}
				})
			}
			// 设置编辑区域高度为 500px
			editor.config.height = 500
			// 创建编辑器
			editor.create()
			this.editor = editor
		},
        methods: {
			handlePreview(file) {
				console.log(file)
			},
			uploadSuccess(response, file, fileList) {
				console.log(response, file, fileList)
			},
			uploadSectionFile(file, fileList) {
				// 后一张覆盖前一张
				if (fileList.length > 0) {
				    this.fileList = [fileList[fileList.length - 1]]
				}
				this.coverFile = file.raw
				console.log(this.coverFile)
			},
			// 获取富文本内容
			getEditorData() {
			    // 通过代码获取编辑器内容
			    let data = this.editor.txt.html()
				// xss过滤
				let safeHtml = this.$xss(data)
				return safeHtml
			},
			// 提交(先上传封面图片，拿到封面url，再上传整个文章)
			onSubmit() {
				let mf = new FormData()
				mf.append('file', this.coverFile)
				uploadImg(mf)
				.then(res => {
					if (res.data) {
						let coverUrl = res?.data[0]?.imgPath ?? ''
						let formdata = this.form
						formdata.id = this.$uid()
						formdata.content = this.getEditorData()
						formdata.addTime = getCurrentTime()
						formdata.cover = coverUrl
						uploadArticle(formdata)
						.then(res => {
							let {data} = res
							if (data) {
								if (data.code === 0) {
                                    this.$socket.emit('submit', { name: this.form.author })
									this.$message({
										message: res.msg,
										type: 'success'
									})
									this.$router.replace({
										path: '/home/manage/none',
										name: 'none'
									})
								}
							} else {
								this.$message({
									message: res.msg,
									type: 'warning'
								})
							}
						})
						.catch()
					} else {
						this.$message({
							message: res.msg,
							type: 'warning'
						})
					}
				})
				.catch()
			},
			// 取消
			cancel() {
				ElMessageBox.confirm(
					'取消将清空内容，是否继续?',
					'Warning',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				).then(() => {
					this.$message({
						message: '已取消',
						type: 'success'
					})
					this.$router.replace({
						path: '/home/manage/none',
						name: 'none'
					})
				})
				.catch(() => {})
			},
		},
		beforeDestroy() {
		  // 调用销毁 API 对当前编辑器实例进行销毁
		  this.editor.destroy()
		  this.editor = null
		}
    }
</script>

<style lang="scss" scoped>
	.articleDetail {
	    width: 100%;
		padding: 12px;
		box-sizing: border-box;
		.toolbar {
			border: 1px solid #ccc;
			::v-deep .w-e-toolbar {
				z-index: 1 !important;
			}
		}
		.text {
			border: 1px solid #ccc;
			margin-top: 10px;
			min-height: 500px;
			::v-deep .w-e-text-container {
				z-index: 0 !important;
			}
		}
		.content {
			
		}
		.btnGrop {
			margin-top: 10px;
		}
	  }
	  
</style>
